package com.hl.controller;

import com.hl.domain.Articletype;
import com.hl.domain.Book;
import com.hl.service.serviceImpl.ArticletypeServiceImpl;
import com.hl.service.serviceImpl.BookServiceImpl;
import com.hl.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @Author：王祖威
 * @Date ：2024/9/11 20:10
 */
@RestController
@RequestMapping("/book")
public class BookController {

    @Autowired
    private BookServiceImpl bookServiceImpl;

    @GetMapping("/find")
    public R findAll(){
        return R.success(bookServiceImpl.findAll());
    }

    @GetMapping("/findlike")
    public R findlike(String name){
        return R.success(bookServiceImpl.findlike(name));
    }

    @DeleteMapping("/delete")
    public R del(Long id){
        return R.success(bookServiceImpl.deleteByPrimaryKey(id));
    }

    @PostMapping("/add")
    public R add(Book record){
        return R.success(bookServiceImpl.insertSelective(record));
    }

    @PutMapping("/updata")
    public R update(Book record){
        return R.success(bookServiceImpl.updateByPrimaryKeySelective(record));
    }

    @PostMapping("/upload2233")
    public R upload(MultipartFile file) throws IOException {
        String path="D:\\load\\";
        System.out.println("load----------------");

        String originalFilename = file.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString()+ext;
        path += filename;
        file.transferTo(new File(path));
        return R.success("http://localhost:8080/book/down2233?fileName=D:/load/"+filename);
    }

    @GetMapping("/down2233")
    public void down(HttpServletResponse response, String fileName) throws IOException {
        // 原生servlet
        File file = new File(fileName);
        InputStream inputStream = new FileInputStream(file);
        ServletOutputStream outputStream = response.getOutputStream();
        FileCopyUtils.copy(inputStream,outputStream);

    }







}
